package com.holdtime.jtt809dataservice.client.socket;

import com.holdtime.jtt809dataservice.client.handler.SubordinatePlatformClientHandler;
import com.holdtime.jtt809dataservice.common.codec.JTT809Decoder;
import com.holdtime.jtt809dataservice.common.codec.JTT809Encoder;
import com.holdtime.jtt809dataservice.common.filter.MyLoggingFilter;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import protocol.jtt809.JTT809Packet;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * author: sunwei
 * Date: 2025/3/14 19:26
 * Description:
 */
@Slf4j
public class TcpClient {
    private EventLoopGroup workerGroup;
    private Bootstrap bootstrap;
    private Channel channel;
    private String host;
    private int port;
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private Runnable runnable;

    public TcpClient(SubordinatePlatformClientHandler handler, String host, int port) {
        this.host = host; // 保存 host
        this.port = port; // 保存 port
        workerGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        // 设置编码解码器
                        pipeline.addLast(new JTT809Decoder());
                        pipeline.addLast(new JTT809Encoder());
                        // 设置日志过滤器
                        pipeline.addLast(new MyLoggingFilter());
                        // 设置空闲处理器
                        pipeline.addLast(new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
                        // 设置处理handler
                        pipeline.addLast(handler);
                        // 添加连接状态监听逻辑
                        pipeline.addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                if (runnable != null) {
                                    runnable.run();
                                }
                            }

                            @Override
                            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                if (!workerGroup.isShutdown()) {
                                    retryConnect(); // 使用非阻塞的重试逻辑
                                }
                            }
                        });
                    }
                });

        // 设置地址、端口
        bootstrap.remoteAddress(new InetSocketAddress(host, port));
    }

    /**
     * 建立连接
     */
    public boolean connect() {
        try {
            ChannelFuture future = bootstrap.connect().sync();
            channel = future.channel();
            return true;
        } catch (Exception e) {
            log.error("从链路连接失败：{}:{}", host, port, e);
            retryConnect();
        }
        return false;
    }

    private void retryConnect() {
        scheduler.schedule(() -> {
            if (!connect()) {
                retryConnect();
            }
        }, 2, TimeUnit.SECONDS);
    }

    /**
     * 关闭连接
     */
    public void close() {
        if (channel != null) {
            channel.close();
            channel = null;
        }
    }

    /**
     * 释放连接
     */
    public void dispose() {
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * 发送数据
     *
     * @return
     */
    public boolean send(JTT809Packet<?> data) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(data);
            return true;
        }
        return false;
    }

    public boolean send(byte[] data) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(data);
            return true;
        }
        return false;
    }

    public Channel getChannel() {
        return channel;
    }

    /**
     * 判断连接是否已建立
     * @return true if the connection is established and active, false otherwise
     */
    public boolean isConnected() {
        return channel != null && channel.isActive();
    }

    public void setRunnable(Runnable runnable) {
        this.runnable = runnable;
    }
}
